package com.xof.phonecall.base

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.xof.phonecall.component.dialog.LoadingDialogipetrpide
import com.xof.phonecall.component.dialog.MessageDialog
import com.xof.phonecall.network.NetworkException

abstract class BaseFragment : Fragment() {

    private lateinit var mLoadingDialogipetrpide: LoadingDialogipetrpide

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let {
            mLoadingDialogipetrpide = LoadingDialogipetrpide(it)
        }
        setViewModelActionsipetrpide()
    }

    /**绑定model*/
    protected abstract fun onBindingViewModelipetrpide(): List<ViewModel>?

    private fun setViewModelActionsipetrpide() {
        val viewModelListipetrpide = onBindingViewModelipetrpide()
        if (!(viewModelListipetrpide.isNullOrEmpty())) {
            viewModelListipetrpide.forEach {
                if (it is IBaseViewModelAction) {
                    it.getLoadingLiveDataipetrpide().observe(viewLifecycleOwner) { showLoading ->
                        if (showLoading)
                            showLodingDialogipetrpide()
                        else
                            dismissLoadingDialogipetrpide()
                    }

                    it.getNetworkExceptionLiveDataipetrpide().observe(viewLifecycleOwner) {
                        onHandleNetworkExcepton(it)
                    }
                }
            }
        }
    }

    protected fun showLodingDialogipetrpide() {
        activity?.let {
            mLoadingDialogipetrpide.showDialogipetrpide(it)
        }
    }

    protected fun dismissLoadingDialogipetrpide() {
        mLoadingDialogipetrpide.dismissDialogipetrpide()
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExcepton(networkExceptionipetrpide: NetworkException) {
        activity?.let {
            if (networkExceptionipetrpide.isAlteripetrpide()) {
                MessageDialog.showDialogipetrpide(it.supportFragmentManager, networkExceptionipetrpide.msg)
            } else {
                Toast.makeText(it, networkExceptionipetrpide.msg, Toast.LENGTH_LONG)
                    .show()
            }
        }
    }
}